package com.lcy.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Controller
public class UploadController {

	@Value("${upload.dir}")
	private String uploadDir;

	@Value("${upload.url}")
	private String uploadUrl;

	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

	/**
	 * 上传文件接口
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = { "/uploadFile" }, method = RequestMethod.POST, produces = {
	"text/javascript;charset=UTF-8" })
	@ResponseBody
	public String uploadFile(HttpServletRequest request, HttpServletResponse response)
			throws IllegalStateException, IOException {
		// 创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 判断 request 是否有文件上传,即多部分请求
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得request中的所有文件名
			Iterator<String> iter = multiRequest.getFileNames();
			// 此处只上传单个文件，如果需要多个文件只需要改为while循环上传
			if (iter.hasNext()) {
				// 记录上传过程起始时的时间，用来计算上传时间
				int pre = (int) System.currentTimeMillis();
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null) {
					// 取得当前上传文件的文件名称
					String myFileName = file.getOriginalFilename();
					// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
					File ff = new File(this.uploadDir);
					if (!ff.exists()) {
						ff.mkdirs();
					}

					File f = new File(this.uploadDir + myFileName);
					// 可能需要重新命名文件
					f.createNewFile();
					logger.info("上传文件路径：" + f.getAbsolutePath() + "   " + f.getPath());
					if (!StringUtils.isEmpty(myFileName.trim())) {
						FileCopyUtils.copy(file.getBytes(), f);
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					logger.info("上传花费时间：" + (finaltime - pre));
					return this.uploadUrl + myFileName;
				}

			}
		}
		return "fail";
	}
}
